package main

import (
	"database/sql"
	"fmt"
	"log"
	"os"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

type User struct {
	ID           uint
	Name         string
	Email        *string
	Age          uint8
	Birthday     *time.Time
	MemberNumber sql.NullString
	ActivatedAt  sql.NullTime
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

func main() {
	dsn := "root:root@tcp(192.168.1.11:3306)/gorm_test?charset=utf8mb4&parseTime=True&loc=Local"

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold:             time.Second, // Slow SQL threshold
			LogLevel:                  logger.Info, // Log level
			IgnoreRecordNotFoundError: true,        // Ignore ErrRecordNotFound error for logger
			Colorful:                  true,        // Disable color
		},
	)

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger,
	})
	if err != nil {
		panic(err)
	}

	var user User
	var users []User

	//获取第一条记录（主键升序）
	//db.First(&user)
	//fmt.Println(user.ID)

	//db.Take(&user)
	//fmt.Println(user.ID)

	//db.Last(&user)
	//fmt.Println(user.ID)

	//result := db.First(&user)
	//fmt.Println(result.RowsAffected) // 返回找到的记录数
	//// 检查 ErrRecordNotFound 错误
	//if errors.Is(result.Error, gorm.ErrRecordNotFound) {
	//	errors.New("无记录")
	//}

	//用主键查询
	//SELECT * FROM `users` WHERE `users`.`id` = 10 ORDER BY `users`.`id` LIMIT 1
	//db.First(&user, 10)
	//fmt.Println(user.Name)

	//SELECT * FROM `users` WHERE `users`.`id` = '10' ORDER BY `users`.`id` LIMIT 1
	//db.First(&user, "10")
	//fmt.Println(user.Name)

	//uuid
	//SELECT * FROM `users` WHERE id = '1b74413f-f3b8-409f-ac47-e8c062e3472a' ORDER BY `users`.`id` LIMIT 1
	db.First(&user, "id = ?", "1b74413f-f3b8-409f-ac47-e8c062e3472a")

	result := db.Find(&users, []int{5, 6, 7})
	fmt.Println("共查询记录：", result.RowsAffected)
	for _, user := range users {
		fmt.Println("user.name:", user.Name)
	}
}
